import { ref, reactive, computed, watch } from "vue";
import { useSearchStore } from "../../store/search";
import { useUserStore } from "../../store/user"
import { getFieldsConfig } from "@/config";
import moment from "moment";
import _ from "lodash"
import { nextTick } from "process";

export const useFilterFieldHooks = (emits: any) => {
  const store = useSearchStore();

  const userStore = useUserStore()

  const userInfo: any = computed(() => userStore.userInfo)




  // 获取当前的搜索大类
  const currConfig = computed(() => {
    return getFieldsConfig(store)["news"];
  });

  /**
   * 筛选逻辑
   */
  // 表单
  const globalArea = computed(() => store.globalArea.id)
  const form: any = reactive({
    // "1": { informationRange: ["1"] },
    // "2": { policyRange: ["1"] },
    // "3": {},
    // "4": { informationRange: ["1"] },
    "1": { searchDistrict: [],informationRange:['1']},
    "2": { searchDistrict: [],policyRange:['1','2'], },
    "3": { searchDistrict: [],orgNatures:['1','2']  },
    "4": { searchDistrict: [],informationRange:['1'] },
    globalAreaID: globalArea.value
  })
  //设置地区选择组件默认值
  // form[store.searchType] = userInfo.value.parkAreaIds

  // 发布时间
  const publishTime = ref<any[]>([moment().subtract(3, 'years'), moment()])
  const timeChange = (e: any) => {
    form[store.searchType]["publishStartTime"] = moment(e[0]).format("YYYY-MM-DD")
    form[store.searchType]["publishEndTime"] = moment(e[1]).format("YYYY-MM-DD")
  }
  // 立项金额区间
  const priceArea = reactive<any>({})

  // 年度 项目批次
  // const years =

  // 层级选择框配置
  const selectConfig = {
    checkStrictly: true,
    value: "id",
  };

  // 选择标签方法
  const checkTag = (key: string, isRadio: boolean, idx: any) => {
    if (isRadio) {
      form[store.searchType][key] = form[store.searchType][key] && form[store.searchType][key] === idx ? "" : idx
      if (key === 'publishTime' && form[store.searchType][key] === '4') {
        form[store.searchType]["publishStartTime"] = moment(publishTime.value[0]).format("YYYY-MM-DD")
        form[store.searchType]["publishEndTime"] = moment(publishTime.value[1]).format("YYYY-MM-DD")
      } else {
        delete form[store.searchType]["publishStartTime"]
        delete form[store.searchType]["publishEndTime"]
      }
    } else {
      // if ((key === 'informationRange' || key === 'policyRange') && form[store.searchType][key]?.length === 1 && form[store.searchType][key].includes(idx)) {
      //   ElMessage({
      //     message: "该筛选维度至少选中一个",
      //     type: "warning",
      //     grouping: true
      //   })
      //   return;
      // }
      form[store.searchType][key] = form[store.searchType][key] || [];
      if (form[store.searchType][key].includes(idx)) {
        // 找到当前idx在form[key]中的真实索引
        const realIdx = form[store.searchType][key].findIndex(
          (item: any) => item === idx
        );
        form[store.searchType][key].splice(realIdx, 1);
      } else {
        form[store.searchType][key].push(idx);
      }
    }
    store.changeform4Linght(form['4'].informationRange);
  };

  // 监听form变化并发送事件给父组件
  watch(
    form,
    (newVal, oldVal) => {
      // 处理下form中的数据
      const params = _.cloneDeep(newVal[store.searchType])
      // if(!params) return
      // 年度和批次参数重新组合
      if (params.years2 && params.years.includes('0')) {
        params.years = params.years?.concat([params.years2 || "0"]).filter((item: any) => item != "0")
      } else {
        params.years = params.years?.filter((item: any) => item != "0")
      }
      if (params.batchs2 && params.batchs.includes('0')) {
        params.batchs = params.batchs?.concat([params.batchs2 || "0"]).filter((item: any) => item != "0")
      } else {
        params.batchs = params.batchs?.filter((item: any) => item != "0")
      }

      emits("formChange", params, false);
    },
    { deep: true, immediate: true }
  );

  // 监听searchType的变化重新请求页面数据
  watch(() => store.searchType, () => {
    emits("formChange", form[store.searchType], true);
  })

  /**
   * 其他方法
   */

  // 检查当前flex容器是否换行
  const containerInfo = ref<any[]>([]);

  const checkFlexWrap = (flexContainer: any) => {
    if (!flexContainer) return;
    // 获取所有容器的宽度
    containerInfo.value = flexContainer.value.map(
      (item: any, index: number) => {
        let sum = 0;
        let hiddenIdx: any = null;

        for (let i = 0; i < item.children.length; i++) {
          const el = item.children[i];
          sum += el.clientWidth;

          if (sum >= item.clientWidth) {
            hiddenIdx = i - 1;

            // 直接隐藏之后的子元素
            for (let j = hiddenIdx; j < item.children.length; j++) {
              const element = item.children[j];
              element.classList.add("hidden");
            }
          }
        }

        return {
          hiddenIdx: hiddenIdx,
          index
        };
      }
    );
  };

  const showMoreTag = (idx: number, flexContainer: any) => {
    const currHandleContainer = flexContainer[idx];
    const items = currHandleContainer.children;

    const hiddenIdx = containerInfo.value[idx].hiddenIdx;

    for (let i = hiddenIdx; i < items.length; i++) {
      const element = items[i];
      element.classList.toggle("hidden");
    }

    containerInfo.value[idx].showMoreBtn =
      !containerInfo.value[idx].showMoreBtn;
  };
  const timeAduio = ref()
  const addressChange = (e: any) => {
    if (e) {
      form[store.searchType].searchDistrict = e
    } else {
      form[store.searchType].searchDistrict = []
    }

  }

  const affirmArea = () => {
    if (priceArea.moneyStart * 1 > priceArea.moneyEnd * 1) {
      return ElMessage({
        type: "warning",
        message: "立项金额区间错误",
        grouping: true
      })
    }
    form[store.searchType] = { ...form[store.searchType], ...priceArea }
  }

  const validateInput = (e: any, key: string) => {
    // 使用正则表达式检查输入是否为正数（包括小数）
    const regex = /^[+]?\d+(\.\d+)?$/;

    priceArea[key] = e.replace(/[^0-9.]+/, "")
    console.log(priceArea, 22);

  }
  const cascader = ref()
  // 重置方法
  const resetFilter = () => {
    let resetVal = {}
    switch (store.searchType) {
      case "1":
        resetVal = { informationRange: ['1'] }
        break;
      case "2":
        resetVal = { policyRange: ['1','2'] }
        break;
      case "3":
        resetVal = { orgNatures:['1','2'] }
        break;
      case "4":
        resetVal = { informationRange: ["1"] }
        priceArea['moneyStart'] = ''
        priceArea['moneyEnd'] = ''
        break;
    }
    timeAduio.value = new Date().getTime()
    form[store.searchType] = resetVal
  }

  return {
    currConfig,
    checkTag,
    form,
    selectConfig,
    checkFlexWrap,
    containerInfo,
    showMoreTag,
    addressChange,
    priceArea,
    affirmArea,
    validateInput,
    publishTime,
    timeChange,
    resetFilter,
    timeAduio
  };
};
